package com.example.smartpark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartpark.dto.VehicleAddDTO;
import com.example.smartpark.dto.VehicleUpdateDTO;
import com.example.smartpark.exception.BusinessException;
import com.example.smartpark.mapper.VehicleMapper;
import com.example.smartpark.model.Vehicle;
import com.example.smartpark.service.VehicleService;
import com.example.smartpark.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 车辆服务实现类
 */
@Slf4j
@Service
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements VehicleService {

    /**
     * 获取用户车辆列表
     *
     * @param userId 用户ID
     * @return 车辆列表
     */
    @Override
    public List<VehicleVO> getUserVehicles(Integer userId) {
        log.info("获取用户车辆列表: userId={}", userId);
        
        // 查询条件：用户ID
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getUserId, userId);
        
        // 查询车辆列表
        List<Vehicle> vehicles = list(queryWrapper);
        
        // 转换为VO列表
        return vehicles.stream()
                .map(this::convertToVehicleVO)
                .collect(Collectors.toList());
    }

    /**
     * 添加车辆
     *
     * @param userId 用户ID
     * @param vehicleAddDTO 添加车辆DTO
     * @return 添加的车辆信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public VehicleVO addVehicle(Integer userId, VehicleAddDTO vehicleAddDTO) {
        log.info("添加车辆: userId={}, vehicleAddDTO={}", userId, vehicleAddDTO);
        
        // 检查车牌号是否已存在
        if (checkPlateNumberExists(vehicleAddDTO.getPlateNumber(), null)) {
            throw new BusinessException("车牌号已存在");
        }
        
        // 创建车辆对象
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleAddDTO, vehicle);
        vehicle.setUserId(userId);
        vehicle.setStatus(1); // 默认为已审核状态
        
        // 如果设置为默认车辆，先将其他车辆设为非默认
        if (vehicleAddDTO.getIsDefault() != null && vehicleAddDTO.getIsDefault() == 1) {
            baseMapper.cancelAllDefaultVehicles(userId);
        }
        
        // 保存车辆信息
        boolean success = save(vehicle);
        if (!success) {
            throw new BusinessException("添加车辆失败");
        }
        
        return convertToVehicleVO(vehicle);
    }

    /**
     * 更新车辆信息
     *
     * @param userId 用户ID
     * @param vehicleId 车辆ID
     * @param vehicleUpdateDTO 更新车辆DTO
     * @return 更新后的车辆信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public VehicleVO updateVehicle(Integer userId, Integer vehicleId, VehicleUpdateDTO vehicleUpdateDTO) {
        log.info("更新车辆: userId={}, vehicleId={}, vehicleUpdateDTO={}", userId, vehicleId, vehicleUpdateDTO);
        
        // 查询车辆是否存在并属于当前用户
        Vehicle vehicle = getVehicleByIdAndUserId(vehicleId, userId);
        
        // 如果更新了车牌号，检查是否已存在
        if (vehicleUpdateDTO.getPlateNumber() != null && 
                !vehicleUpdateDTO.getPlateNumber().equals(vehicle.getPlateNumber()) && 
                checkPlateNumberExists(vehicleUpdateDTO.getPlateNumber(), vehicleId)) {
            throw new BusinessException("车牌号已存在");
        }
        
        // 更新车辆信息
        boolean needsUpdate = false;
        
        if (vehicleUpdateDTO.getPlateNumber() != null && !vehicleUpdateDTO.getPlateNumber().equals(vehicle.getPlateNumber())) {
            vehicle.setPlateNumber(vehicleUpdateDTO.getPlateNumber());
            needsUpdate = true;
        }
        
        if (vehicleUpdateDTO.getVehicleType() != null && !vehicleUpdateDTO.getVehicleType().equals(vehicle.getVehicleType())) {
            vehicle.setVehicleType(vehicleUpdateDTO.getVehicleType());
            needsUpdate = true;
        }
        
        if (vehicleUpdateDTO.getVehicleColor() != null && !vehicleUpdateDTO.getVehicleColor().equals(vehicle.getVehicleColor())) {
            vehicle.setVehicleColor(vehicleUpdateDTO.getVehicleColor());
            needsUpdate = true;
        }
        
        if (vehicleUpdateDTO.getVehicleBrand() != null && !vehicleUpdateDTO.getVehicleBrand().equals(vehicle.getVehicleBrand())) {
            vehicle.setVehicleBrand(vehicleUpdateDTO.getVehicleBrand());
            needsUpdate = true;
        }
        
        if (vehicleUpdateDTO.getVehicleModel() != null && !vehicleUpdateDTO.getVehicleModel().equals(vehicle.getVehicleModel())) {
            vehicle.setVehicleModel(vehicleUpdateDTO.getVehicleModel());
            needsUpdate = true;
        }
        
        // 处理默认车辆设置
        if (vehicleUpdateDTO.getIsDefault() != null && !vehicleUpdateDTO.getIsDefault().equals(vehicle.getIsDefault())) {
            // 如果设置为默认车辆，先将其他车辆设为非默认
            if (vehicleUpdateDTO.getIsDefault() == 1) {
                baseMapper.cancelAllDefaultVehicles(userId);
            }
            vehicle.setIsDefault(vehicleUpdateDTO.getIsDefault());
            needsUpdate = true;
        }
        
        // 保存更新
        if (needsUpdate) {
            boolean success = updateById(vehicle);
            if (!success) {
                throw new BusinessException("更新车辆信息失败");
            }
        }
        
        return convertToVehicleVO(vehicle);
    }

    /**
     * 删除车辆
     *
     * @param userId 用户ID
     * @param vehicleId 车辆ID
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteVehicle(Integer userId, Integer vehicleId) {
        log.info("删除车辆: userId={}, vehicleId={}", userId, vehicleId);
        
        // 查询车辆是否存在并属于当前用户
        Vehicle vehicle = getVehicleByIdAndUserId(vehicleId, userId);
        
        // 删除车辆
        return removeById(vehicleId);
    }

    /**
     * 检查车牌号是否已存在
     *
     * @param plateNumber 车牌号
     * @param excludeVehicleId 排除的车辆ID（用于更新时）
     * @return 是否存在
     */
    @Override
    public boolean checkPlateNumberExists(String plateNumber, Integer excludeVehicleId) {
        log.info("检查车牌号是否已存在: plateNumber={}, excludeVehicleId={}", plateNumber, excludeVehicleId);
        
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getPlateNumber, plateNumber);
        
        // 如果是更新操作，排除当前车辆
        if (excludeVehicleId != null) {
            queryWrapper.ne(Vehicle::getId, excludeVehicleId);
        }
        
        return count(queryWrapper) > 0;
    }
    
    /**
     * 根据车辆ID和用户ID获取车辆信息
     *
     * @param vehicleId 车辆ID
     * @param userId 用户ID
     * @return 车辆信息
     */
    private Vehicle getVehicleByIdAndUserId(Integer vehicleId, Integer userId) {
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getId, vehicleId)
                   .eq(Vehicle::getUserId, userId);
        
        Vehicle vehicle = getOne(queryWrapper);
        if (vehicle == null) {
            throw new BusinessException("车辆不存在或不属于当前用户");
        }
        
        return vehicle;
    }
    
    /**
     * 将Vehicle对象转换为VehicleVO对象
     *
     * @param vehicle Vehicle对象
     * @return VehicleVO对象
     */
    private VehicleVO convertToVehicleVO(Vehicle vehicle) {
        if (vehicle == null) {
            return null;
        }
        
        VehicleVO vehicleVO = new VehicleVO();
        BeanUtils.copyProperties(vehicle, vehicleVO);
        return vehicleVO;
    }

    @Override
    public List<Integer> getUserVehicleIds(Integer userId) {
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getUserId, userId)
                   .eq(Vehicle::getStatus, 1); // 只查询已审核的车辆
        return this.list(queryWrapper).stream()
                .map(Vehicle::getId)
                .collect(Collectors.toList());
    }
} 